import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subject } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd';
import { SongService } from '@services/song.service';
import { BatchActionsService } from '@store/batch-actions.service';
import { getCurrentSong, getPlayer } from '@store/selectors/player.selector';
import { Singer, Song } from '@services/data-types/common.type';
import { LyricLine, WyyLyric } from '@share/wyy-ui/wyy-player/wyy-player-panel/wyy-lyric';
import { select, Store } from '@ngrx/store';
import { AppStoreModule } from '@store/index';
import { ModalTypes, ShareInfo } from '@store/reducers/member.reducer';
import { User } from '@services/data-types/member.type';
import { StorageService } from '@services/storage.service';
import { MemberService } from '@services/member.service';

@Component({
  selector: 'app-song-info',
  templateUrl: './song-info.component.html',
  styleUrls: ['./song-info.component.less']
})
export class SongInfoComponent implements OnInit, OnDestroy {
  currentIndex: number;
  song: Song;
  user: User;
  currentSong: Song;
  lyric: LyricLine[];
  // 歌曲详情描述信息
  description = {
    long: '',
    short: ''
  };
  controlDesc = {
    isExpand: false,
    label: '展开',
    iconCls: 'down'
  };
  private destroy$ = new Subject<void>();
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private store$: Store<AppStoreModule>,
    private songServe: SongService,
    private memberService: MemberService,
    private storageService: StorageService,
    private nzMessageServe: NzMessageService,
    private batchActionsService: BatchActionsService
  ) {
    this.route.data.pipe(map(res => res.songInfo)).subscribe(([song, lyric]) => {
      this.song = song;
      this.lyric = new WyyLyric(lyric).lines;
      this.listenCurrentSong();
    });
  }

  ngOnInit() {
    this.getUserInfo();
  }
  private listenCurrentSong() {
    this.store$.pipe(select(getPlayer), select(getCurrentSong), takeUntil(this.destroy$))
    .subscribe(song => {
      this.currentSong = song;
    });
  }
  private makeTxt(type: string, name: string, makeBy: string | Singer[]): string {
    let needText = '';
    if (Array.isArray(makeBy)) {
      needText = makeBy.map(item => item.name).join('/');
    } else {
      needText = makeBy;
    }
    return `${type}: ${name} -- ${needText}`;
  }
  private getUserInfo() {
    const userId = this.storageService.getStorage('wyyUserId');
    if (userId) {
      this.batchActionsService.setUserId(userId.toString());
      this.memberService.getUserDetail(userId).subscribe(res => {
        this.user = res;
      });
    }
  }
  toggleLyric() {
    this.controlDesc.isExpand = !this.controlDesc.isExpand;
    if (this.controlDesc.isExpand) {
      this.controlDesc.iconCls = 'up';
      this.controlDesc.label = '收起';
    } else {
      this.controlDesc.iconCls = 'down';
      this.controlDesc.label = '展开';
    }
  }
  // 收藏歌曲
  onLikeSong(song: Song) {
    const ids = song.id.toString();
    this.batchActionsService.likeSong(ids);
  }
  // 分享歌曲
  onShareSong(song: Song, type = 'song') {
    const txt = this.makeTxt('歌曲', song.name, song.ar);
    const info: ShareInfo = {id: song.id.toString(), type, txt};
    this.batchActionsService.setShareInfo(info);
  }
  // 添加歌曲到歌单
  onAddSongList(song: Song, isPlay = false) {
    if (!this.currentSong || song.id !== this.currentSong.id) {
      this.songServe.getSongList(song).subscribe(list => {
        // 如果当前歌曲没有url，就不再执行insertSong这个Action
        if (list.length) {
          this.batchActionsService.insertSong(list[0], isPlay);
        } else {
          this.nzMessageServe.create('warning', '无url');
        }
      });
    }
  }
  skipToSinger(path: string, id: string): void {
    if (this.user) {
      this.router.navigate([path, id]).then();
    } else {
      this.batchActionsService.controlModalVisible(true, ModalTypes.LoginByPhone);
    }
  }
  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
